/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.cn360.batch.BuildCn360CatsJob
   Module Description   :

   Date Created      : 2011/6/21
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.cn360.batch;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

import com.csvreader.CsvWriter;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.thread.batch.AbstractRunJob;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.cn360.remote.RemoteCn360ProductService;

/**
 * @author jeffma
 * 
 */
public class BuildCn360CatsJob extends AbstractRunJob {

	private CategoryService categoryService;

	/** default constructor */
	public BuildCn360CatsJob(CategoryService categoryService) {
		super("BuildCn360CatsJob");
		this.categoryService = categoryService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.core.thread.batch.AbstractRunJob#execute()
	 */
	@Override
	public void execute() {
		String now = DateUtil.convertDateToString("yyyyMMdd", DateUtil.getCurrentTime());
		String feedFile = ServerValue.getFrontApachePath() + "3party_ex" + File.separator + "360cn" + File.separator
				+ "yaodian100_c_" + now + ".csv";
		File feedFileObj = new File(feedFile);
		if (feedFileObj.exists()) {
			feedFileObj.delete();
		}
		try {
			CommonCriteria cri = new CommonCriteria();
			cri.addEq("isVisible", "Y");
			cri.addEq("isDelete", "N");
			cri.addEq("level", "0");
			cri.addLe("startDate", new Date());
			cri.addGe("endDate", new Date());
			List<Category> categories = categoryService.getList(0, -1, cri, new String[] { "categoryPath asc" });

			CsvWriter writer = new CsvWriter(feedFile, ',', Charset.forName("gb2312"));
			writer.writeRecord(new String[] { "bid", "category_id", "category_name", "category_pid", "isfinal" });
			int count = 0;
			for (Category c : categories) {
				writer.writeRecord(new String[] { RemoteCn360ProductService.BID, c.getId().toString(), c.getName(),
						c.getParentId().toString(), "true" });
				count++;

				if (count % 200 == 0) {
					writer.flush();
				}
			}
			writer.flush();
			writer.close();
		} catch (Exception e) {
			logger.error("写档错误", e);
		}
	}
}
